#include <lwip/tcp.h>
#include "mch.h"

err_t  recv_cb(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
  u16_t len = 0;
  //struct pbuf *pit;

  if (p)
    len = p->tot_len;

  mch_printf("receive %d data from server\n", len);

  tcp_recved(pcb, len);

  tcp_close(pcb);
  err = ERR_OK;
  return err;

}


static err_t  connect_cb(void *arg, struct tcp_pcb *pcb, err_t err)
{
  u8_t data[]= "Hello";

  mch_printf("Client:connected to %s:%d\n",
      ipaddr_ntoa(&pcb->remote_ip),
      pcb->remote_port);  

  tcp_write(pcb, data, sizeof(data), 0);
  err = ERR_OK;
  return err;
  
}


int client_init(struct ip_addr *ipaddr, u16_t port)
{
  struct tcp_pcb *pcb;
  err_t err;

  pcb = tcp_new();
  if (!pcb)
  {
      mch_printf("tcp_new failed\n");
      return -1;
  }

  err = tcp_bind(pcb, IP_ADDR_ANY, 0); 
  if (err != ERR_OK) 
  {
      mch_printf("tcp_bind failed\n");
      return -1;
  }

  tcp_connect(pcb, ipaddr, port, connect_cb);
  tcp_recv(pcb, recv_cb);

  return 0;
}



